package com.iogogogo.tenant.config.dao;

import com.iogogogo.tenant.domain.pojo.TenantDataSourceConfig;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Created by tao.zeng on 2021/8/8.
 */
@Repository
public class DataSourceConfigDao {

    private final JdbcTemplate jdbcTemplate;

    public DataSourceConfigDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<TenantDataSourceConfig> getAll() {
        String sql = "select * from tenant_datasource_config";
        return this.jdbcTemplate.query(sql, resultMap());
    }

    public TenantDataSourceConfig getByName(String name) {
        String sql = "select * from tenant_datasource_config where name = ?";
        List<TenantDataSourceConfig> list = this.jdbcTemplate.query(sql, resultMap(), name);
        return list.size() == 0 ? null : list.get(0);
    }

    private RowMapper<TenantDataSourceConfig> resultMap() {
        return (rs, rowNum) -> {
            TenantDataSourceConfig tenantDataSourceConfig = new TenantDataSourceConfig();
            tenantDataSourceConfig.setId(rs.getLong("id"));
            tenantDataSourceConfig.setName(rs.getString("name"));
            tenantDataSourceConfig.setUsername(rs.getString("username"));
            tenantDataSourceConfig.setPassword(rs.getString("password"));
            tenantDataSourceConfig.setUrl(rs.getString("url"));
            tenantDataSourceConfig.setDriverClassName(rs.getString("driver"));
            tenantDataSourceConfig.setStatus(rs.getInt("status"));
            tenantDataSourceConfig.setCreateTime(rs.getObject("create_time", LocalDateTime.class));
            tenantDataSourceConfig.setUpdateTime(rs.getObject("update_time", LocalDateTime.class));
            return tenantDataSourceConfig;
        };
    }
}
